今天分享的class又被稱為 [類別] 是 ECMAScript 6 中的語法,用來作為建立新的物件的統一模板,可以把重複性的城市法封裝起來,便於使用,不熟悉的話可以先去MDN看看介紹,會比較清楚。
想要做出這樣的婚禮賀卡,有背景,文字,不規則的小雪花,於是雪花可以由class來模組化,封裝成一個不斷產生雪花得產雪機。
可以區分成底圖,遮罩剪裁,文字與雪花四個步驟,由於會用到遮罩,所以我們設定兩個畫布
function setup(){
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB, 360, 100, 100, 100);
  noLoop()
  //第二層layer設定
  layer2 = createGraphics(width, 560);
  layer2.colorMode(HSB, 360, 100, 100, 100);
  layer2.rectMode(CENTER);
  layer2.textFont(font);
  layer2.textAlign(CENTER, CENTER);
  layer2.imageMode(CENTER);
  layer2.textSize(128);
}
function draw(){
  let ww = width/bgImage.width
  image(bgImage,0, 0 ,bgImage.width* ww, bgImage.height *ww);
  layer2.background('#f6dbc6');//359, 34, 95
  image(layer2, 0, height/2-layer2.height/2)
}
class Petal{ 
  constructor(){
    this.radius = random(4,20); //大小隨機,半徑
    this.locationC = 
    createVector(  //向量位置
      random(0,width),  //主畫布的
      random(0,height),
    )
  }
  snow(i ){
    if(i%2){
      layer2.rect(this.locationC.x , this.locationC.y , this.radius*3, this.radius*3, 4 )
    }else{
      layer2.ellipse(this.locationC.x , this.locationC.y , this.radius*2 )
    }
  }
}
function setup(){
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB, 360, 100, 100, 100);
  noLoop()
  //第二層layer設定
  layer2 = createGraphics(width, 560);
  layer2.colorMode(HSB, 360, 100, 100, 100);
  layer2.rectMode(CENTER);
  layer2.textFont(font);
  layer2.textAlign(CENTER, CENTER);
  layer2.imageMode(CENTER);
  layer2.textSize(128);
  for (let i = 0; i < 50; i++) { //建立20個隨機球球
    petals.push(new Petal()); //並且放在一個陣列裡面
  }
}
function draw(){
  let ww = width/bgImage.width
  image(bgImage,0, 0 ,bgImage.width* ww, bgImage.height *ww);
  layer2.background('#f6dbc6');
  layer2.erase(100,100);
  layer2.strokeWeight(3);
  layer2.text('HAPPY WEDDING', layer2.width/2, layer2.height/2-55);
  layer2.textSize(48);
  layer2.text(
    'DEAR FRIEND',
    layer2.width/2, layer2.height/2+115
  );
  
  layer2.noErase();
  for (let i = 0; i < petals.length; i++) {
    petals[i].show(i); //呼叫下雪
  }
  image(layer2, 0, height/2-layer2.height/2)
}
設計更多的method,還可以移動雪花,或者製造出下雪到一半雪花消逝的視覺效果。謝謝大家今天的收看